# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class Equipment(models.Model):
    """设备主表模型"""
    _name = 'device.equipment'
    _description = '设备管理'
    _order = 'create_time desc, name'
    _rec_name = 'name'
    _inherit = ['device.permission.mixin']
    
    # 基础信息
    name = fields.Char('设备名称', required=True)
    code = fields.Char('设备编号', required=True)
    model = fields.Char('设备型号')
    description = fields.Text('设备描述')
    
    # 分类和位置
    category_id = fields.Many2one('device.category', '设备类别', required=True)
    category_name = fields.Char('设备类别名称', related='category_id.name', store=True)
    department_id = fields.Many2one('device.department', '所属部门', required=True)
    workshop_id = fields.Many2one('device.workshop', '设备位置（车间）', required=True)
    
    # 使用人和负责人
    user_id = fields.Many2one('device.user', '设备使用人')
    manager_id = fields.Many2one('device.user', '设备负责人')
    
    # 设备状态
    status = fields.Selection([
        ('normal', '正常'),
        ('maintenance', '维护中'),
        ('fault', '故障'),
        ('scrap', '报废'),
        ('idle', '闲置')
    ], string='设备状态', default='normal', required=True)
    
    # 时间相关
    purchase_date = fields.Date('购买日期')
    warranty_end_date = fields.Date('保修截止时间')
    last_maintenance_date = fields.Datetime('最近维护时间', compute='_compute_last_maintenance_date', store=True)
    
    # 使用情况
    usage_frequency = fields.Selection([
        ('daily', '每天'),
        ('weekly', '每周'),
        ('monthly', '每月')
    ], string='使用频率', default='daily')
    usage_hours = fields.Float('使用时长（小时）', help='总使用时长')
    
    # 文件附件
    attachment_ids = fields.One2many('ir.attachment', 'res_id', 
                                   domain=[('res_model', '=', 'device.equipment')], 
                                   string='相关附件')
    
    # 附件URL字段 - 存储通过公共上传接口上传的文件URL
    attachment_urls = fields.Text('附件URL列表', help='存储文件URL，多个URL用换行分隔')
    image_url = fields.Char('设备图片URL', help='设备主图片的URL')
    manual_url = fields.Char('说明书URL', help='设备说明书文件的URL')
    certificate_url = fields.Char('合格证URL', help='设备合格证文件的URL')
    
    # 创建和修改信息
    create_time = fields.Datetime('创建时间', default=fields.Datetime.now)
    update_time = fields.Datetime('更新时间', default=fields.Datetime.now)
    create_by = fields.Char('创建者')
    update_by = fields.Char('更新者')
    remark = fields.Text('备注')
    
    # 统计字段
    maintenance_count = fields.Integer('维保次数', compute='_compute_maintenance_count')
    training_count = fields.Integer('培训次数', compute='_compute_training_count')
    inspection_count = fields.Integer('巡检次数', compute='_compute_inspection_count')
    repair_count = fields.Integer('报修次数', compute='_compute_repair_count')
    
    @api.depends('maintenance_ids')
    def _compute_last_maintenance_date(self):
        """计算最近维护时间"""
        for equipment in self:
            latest_maintenance = self.env['device.maintenance'].search([
                ('equipment_id', '=', equipment.id)
            ], order='end_date desc', limit=1)
            equipment.last_maintenance_date = latest_maintenance.end_date if latest_maintenance else False
    
    @api.depends()
    def _compute_maintenance_count(self):
        for equipment in self:
            equipment.maintenance_count = self.env['device.maintenance'].search_count([
                ('equipment_id', '=', equipment.id)
            ])
    
    @api.depends()
    def _compute_training_count(self):
        for equipment in self:
            equipment.training_count = self.env['device.training'].search_count([
                ('equipment_id', '=', equipment.id)
            ])
    
    @api.depends()
    def _compute_inspection_count(self):
        for equipment in self:
            equipment.inspection_count = self.env['device.inspection'].search_count([
                ('equipment_id', '=', equipment.id)
            ])
    
    @api.depends()
    def _compute_repair_count(self):
        for equipment in self:
            equipment.repair_count = self.env['device.repair'].search_count([
                ('equipment_id', '=', equipment.id)
            ])
    
    # 关联记录
    maintenance_ids = fields.One2many('device.maintenance', 'equipment_id', '维保记录')
    training_ids = fields.One2many('device.training', 'equipment_id', '培训记录')
    inspection_ids = fields.One2many('device.inspection', 'equipment_id', '巡检记录')
    verification_ids = fields.One2many('device.verification', 'equipment_id', '验证记录')
    calibration_ids = fields.One2many('device.calibration', 'equipment_id', '校准记录')
    repair_ids = fields.One2many('device.repair', 'equipment_id', '报修记录')
    
    @api.constrains('code')
    def _check_code_unique(self):
        for record in self:
            if self.search_count([('code', '=', record.code), ('id', '!=', record.id)]) > 0:
                raise ValidationError(f'设备编号 {record.code} 已存在，请使用其他编号。')
    
    @api.constrains('warranty_end_date', 'purchase_date')
    def _check_warranty_date(self):
        for record in self:
            if record.warranty_end_date and record.purchase_date:
                if record.warranty_end_date < record.purchase_date:
                    raise ValidationError('保修截止时间不能早于购买日期。')
    
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            vals['create_time'] = fields.Datetime.now()
            if self.env.user:
                vals['create_by'] = self.env.user.name
        return super().create(vals_list)
    
    def write(self, vals):
        vals['update_time'] = fields.Datetime.now()
        if self.env.user:
            vals['update_by'] = self.env.user.name
        return super().write(vals)
    
    def action_view_maintenance(self):
        """查看维保记录"""
        return {
            'name': '设备维保记录',
            'type': 'ir.actions.act_window',
            'res_model': 'device.maintenance',
            'view_mode': 'tree,form',
            'domain': [('equipment_id', '=', self.id)],
            'context': {'default_equipment_id': self.id}
        }
    
    def action_view_training(self):
        """查看培训记录"""
        return {
            'name': '设备培训记录',
            'type': 'ir.actions.act_window',
            'res_model': 'device.training',
            'view_mode': 'tree,form',
            'domain': [('equipment_id', '=', self.id)],
            'context': {'default_equipment_id': self.id}
        }
    
    def action_view_inspection(self):
        """查看巡检记录"""
        return {
            'name': '设备巡检记录',
            'type': 'ir.actions.act_window',
            'res_model': 'device.inspection',
            'view_mode': 'tree,form',
            'domain': [('equipment_id', '=', self.id)],
            'context': {'default_equipment_id': self.id}
        }
    
    def action_view_repair(self):
        """查看报修记录"""
        return {
            'name': '设备报修记录',
            'type': 'ir.actions.act_window',
            'res_model': 'device.repair',
            'view_mode': 'tree,form',
            'domain': [('equipment_id', '=', self.id)],
            'context': {'default_equipment_id': self.id}
        }
